// 消息中心
import React, { useState, useEffect, useRef, useCallback } from 'react'
import './message.scss'
import moment from 'moment'
import MyTable from '../../../components/table/table'
import { Button } from 'antd'
import {
  serviceGetInnerMessage,
  serviceUpdateInnerMessageHasRead,
} from '../../../request/innermessage'
import { spawn } from 'child_process'

const InnerMessage: React.FC = function () {
  const tableRef = useRef<any>(null)
  const [selectedRowKeys, setSelectedRowKeys] = useState([])
  const tableColumns = [
    {
      title: '序号',
      width: 60,
      render: (currentRowValue: any, currentRowData: any, index: number) =>
        index + 1,
      align: 'center',
    },
    {
      className: 'unread-row',
      title: '',
      dataIndex: 'hasRead',
      width: 12,
      align: 'center',
      render: (hasRead: boolean) => !hasRead && <i className="unread-dot">●</i>,
    },
    {
      title: '标题内容',
      dataIndex: 'content',
      render: (content: any) => <div className="ellipsis-two">{content}</div>,
    },
    {
      title: '提交时间',
      dataIndex: 'createdAt',
      width: 150,
      align: 'center',
      fixed: 'right',
    },
    {
      title: '类型',
      dataIndex: 'title',
      width: 100,
      align: 'center',
      fixed: 'right',
    },
  ]
  const getInnerMessage = useCallback((params?: object) => {
    return serviceGetInnerMessage(params).then(res => {
      if (res.data.success) {
        res.data.data.rows.forEach((item: any) => {
          item.createdAt = moment(item.createdAt).format('YYYY-MM-DD HH:mm')
        })
      }
      return res
    })
  }, [])

  const handleAction = useCallback(
    (type: 1 | 2) => {
      let params = selectedRowKeys.join()
      if (type === 2) params = 'all'
      serviceUpdateInnerMessageHasRead(params).then(res => {
        if (res.data.success) {
          setSelectedRowKeys([])
          tableRef.current.getTableData()
        }
      })
    },
    [selectedRowKeys, tableRef, setSelectedRowKeys],
  )

  useEffect(() => {
    tableRef.current.getTableData()
  }, [tableRef])

  return (
    <div className="inner-message">
      <MyTable
        ref={tableRef}
        getTableData={getInnerMessage}
        columns={tableColumns}
        rowSelection={{
          selectedRowKeys,
          onChange: (selectedKeys: any) => {
            setSelectedRowKeys(selectedKeys)
          },
        }}
      ></MyTable>
      <div className="action-group">
        <Button
          onClick={handleAction.bind(null, 1)}
          disabled={selectedRowKeys.length <= 0}
        >
          标记已读
        </Button>
        <Button
          onClick={handleAction.bind(null, 2)}
          disabled={selectedRowKeys.length <= 0}
        >
          全部已读
        </Button>
      </div>
    </div>
  )
}

export default InnerMessage
